package emediashared.model;

import java.net.InetAddress;

import org.eclipse.core.resources.ResourcesPlugin;

import emediashared.SharedActivator;
import emediashared.ui.PreferencesDialog;

public class HttpSharedServer  implements ISharedServer{
	private static ISharedServer instance;
	private String userName;
	private String address;
	private int port = 8080;
	private boolean connected;
	
	public static ISharedServer getInstance() {
		try {
			if (instance == null) {
				instance = new HttpSharedServer();
			}
			if (!instance.isConnected()) {
				instance.reconnect();
			}
		} catch (Exception e) {
			SharedActivator.showAndLogError(e);
		}
		return instance;
	}
	
	private boolean sampleClient;
	private InetAddress localHost;
	
	{
		try {
			ResourcesPlugin.getWorkspace();
		} catch (IllegalStateException e) {
			sampleClient = true;
		}
	}
	
	/* (non-Javadoc)
	 * @see emediashared.model.ISharedServer#isConnected()
	 */
	@Override
	public boolean isConnected() {
		return connected;
	}

	private boolean connect() {
		if (sampleClient) {
			userName = "Prasad";
		} else {
			userName = PreferencesDialog.getUserName();
		}

		try {
			localHost = InetAddress.getLocalHost();
			if (localHost.isLoopbackAddress()) {
				System.out.println("Loopback=" + localHost.isLoopbackAddress());
				if (sampleClient) {
					// retry mechanism
					int sleepTime = sampleClient ? 1000 : 100000;
					Thread.sleep(sleepTime);
					reconnect();
					if (connected) {
						return true;
					}
				} else {
					return false;
				}
			}
			address = localHost.getHostAddress();
			connected = true;
		} catch (Exception e) {
			System.out.println("can't get inet address.");
		}
		return connected;
	}

	/* (non-Javadoc)
	 * @see emediashared.model.ISharedServer#reconnect()
	 */
	@Override
	public void reconnect() throws Exception {
		if (!connected) {
			connect();
		} 
	}
	
	public int getPort() {
		return port;
	}
	
	/* (non-Javadoc)
	 * @see emediashared.model.ISharedServer#getAddress()
	 */
	@Override
	public String getAddress() {
		return address;
	}
	
	/* (non-Javadoc)
	 * @see emediashared.model.ISharedServer#getUrl()
	 */
	@Override
	public String getUrl() {
       return address + SharedRmiClient.PORT_SEPARATOR + port;
	}
	
	public String getUserName() {
		return userName;
	}
	
}
